<?php

class UserController extends AdminController {

    const MODEL_CLASS_NAME = 'User';

    public function actionIndex() {
	$model = new User(User::SCENARIO_SEARCH);
	$model->unsetAttributes();  // clear any default values

	if (isset($_GET[UserController::MODEL_CLASS_NAME])) {
	    $model->attributes = $_GET[UserController::MODEL_CLASS_NAME];
	}

	$this->render('index', array('model' => $model));
    }

    function actions() {
	return array(
	    'create' => array(
		'class' => 'lib.components.actions.CreateAction',
		'modelClass' => UserController::MODEL_CLASS_NAME,
		//'callback' => 'sendMail',
		'messages' => array('success' => t('MSG_INFO_INSERT_SUCCESS', 'messages', array('{0}' => t('LBL_USER', 'user'))))
	    ),
	    'update' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => UserController::MODEL_CLASS_NAME,
		'validateMethod' => 'validateSuperAdmin',
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_USER', 'user'))))
	    ),
	    'delete' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_USER', 'user')))),
		'validateMethod' => 'validateDelete',
	    ),
	    'active' => array(
		'class' => 'lib.components.actions.LGUpdateAnItemAction',
		'modelClass' => UserController::MODEL_CLASS_NAME,
		'validateMethod' => 'validateActiveAction',
		'customAction' => 'active',
		'itemName' => t('LBL_USER', 'user'),
	    ),
	    'approval' => array(
		'ajaxView' => '_approve',
		'customAction' => 'approval',
		'class' => 'lib.components.actions.DeleteAction',
	    ),
	);
    }

    /**
     * Validate is affected user loggin user or supper admin
     * @param type $models
     * @return \LGMessage
     */
    public function validateActiveAction($models) {
	$msg = null;
	$user = $models[0];

	if ($user->id == Yii::app()->user->id) {
	    $msg = new LGMessage(MsgType::ERROR, t('LBL_NOT_ACTIVE_INACTIVE_YOURSELF', 'user'));
	} else if ($user->username == user()->superAdmin) {
	    $msg = new LGMessage(MsgType::ERROR, t('LBL_NOT_ACTIVE_INACTIVE_SUPERADMIN', 'user'));
	}

	return $msg;
    }

    /**
     * 
     * @param array<User> $models
     * @param LGActiveItemAction $action
     * @return \LGMessage
     */
    public function active($models, $action) {
	$msg = NULL;
	$user = $models[0];

	$user->scenario = User::SCENARIO_CHANGE_ACTIVATION_STATUS;

	$isSuccessful = false;

	if ($user->username != user()->superAdmin) {
	    if ($user->active == LGConstant::ACTIVATION_STATUS_YES) {
		$actionName = t('LBL_INACTIVED');
		$user->active = LGConstant::ACTIVATION_STATUS_NO;
	    } else {
		$user->active = LGConstant::ACTIVATION_STATUS_YES;
		$actionName = t('LBL_ACTIVED');
	    }

	    $isSuccessful = $user->save();
	}

	if ($isSuccessful) {
	    $msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_SUCCESS', 'messages', array('{0}' => t('LBL_USER', 'user'), '{1}' => $actionName)));
	} else {
	    $msg = new LGMessage(MsgType::ERROR, $action->messages['error']);
	}

	return $msg;
    }

    /**
     * 
     * @param array<User> $models
     * @param User $model
     * @param LGActiveItemAction $action
     * @return \LGMessage
     */
    public function approval($models) {
	$msg = NULL;
	$user = $models[0];
	$isSuccessful = false;

	if ($user->active || empty($user->active_code)) {
	    $msg = new LGMessage(MsgType::ERROR, t('MSG_ERROR_CAN_NOT_APPROVE', 'user'));
	} else {
	    $isSuccessful = $this->sendActivationMail($user);

	    if ($isSuccessful) {
		$msg = new LGMessage(MsgType::SUCCESS, t('MSG_SENT_ACTIVATION_SUCCESSFULLY', 'user'));
	    } else {
		$msg = new LGMessage(MsgType::ERROR, t('MSG_ERROR_SEND_EMAIL_UNSUCCESSFULLY', 'user'));
	    }
	}
	return $msg;
    }

//    public function sendMail($model) {
//	if ($model->active) {
//	    $body = t('EMAIL_ADDED_BODY', 'authorization', array(
//		'{name}' => $model->first_name . ' ' . $model->last_name, '{username}' => $model->username
//		, '{password}' => $model->new_password));
//	    $body .= t('EMAIL_GENERATED');
//	    sendMail($model->email, $body, t('EMAIL_ADDED_SUBJECT', 'authorization'));
//	} else {
//	    $activation = domain() . url("/authorization/activation", array('email' => $model->email, 'active_code' => $model->active_code));
//	    $body = t('EMAIL_REGISTER_BODY', 'authorization', array(
//		'{name}' => $model->first_name . ' ' . $model->last_name, '{activation}' => $activation));
//	    sendMail($model->email, $body, t('EMAIL_REGISTER_SUBJECT', 'authorization'));
//	}
//    }

    /**
     * 
     * @param User $model
     * @return boolean
     */
    public function sendActivationMail($model) {
	$activation = domain() . SITE_URL . '/signup/activation.html?email=' . $model->email . '&active_code=' . $model->active_code;
	$body = t('EMAIL_ACTIVATION_BODY', 'authorization', array(
	    '{name}' => $model->first_name . ' ' . $model->last_name, '{activation}' => $activation));
	try {
	    $email_to = $model->email;
	    if (param("debugMode") == true) {
		$email_to = param('emailTesting');
	    }

	    return sendMail($email_to, $body, t('EMAIL_ACTIVATION_SUBJECT', 'authorization'));
	} catch (Exception $exc) {
	    return false;
	}
    }

    public function loadModel() {
	$model = null;
	if (isset($_GET['id'])) {
	    $ids = explode(',', $_GET['id']);
	    if (isset($ids)) {
		$criteria = new CDbCriteria;
		$criteria->addInCondition('id', $ids);
		$model = User::model()->findAll($criteria);
	    }
	}
	return $model;
    }

    /**
     * Delete account with belows rules:
     * 	    - Can not delete built-in admin account
     * 	    - Can not delete current account
     * @return \LGMessage
     */
    public function validateDelete($models) {
	//$ids = explode(',', $_GET['id']);
	$msg = NULL;

	/* @var $loggedUser User */
	$loggedUser = User::model()->findByPk(app()->user->id);

	foreach ($models as $user) {
	    if (!$loggedUser->isSuperAdmin() && $user->isSuperAdmin()) {
		$msg = new LGMessage(MsgType::ERROR, t('LBL_NOT_DELETE_SUPERADMIN', 'user'));
		break;
	    }

	    if (!$loggedUser->isSuperAdmin() && !$loggedUser->isAdmin() && $user->isAdmin()) {
		$msg = new LGMessage(MsgType::ERROR, t('LBL_NOT_DELETE_ADMIN', 'user'));
		break;
	    }
	    if ($user->username === app()->user->superAdmin) {
		$msg = new LGMessage(MsgType::ERROR, t('LBL_NOT_DELETE_SUPERADMIN', 'user'));
		break;
	    }

	    if ($user->id === Yii::app()->user->id) {
		$msg = new LGMessage(MsgType::ERROR, t('LBL_NOT_DELETE_YOURSELF', 'user'));
		break;
	    }
	}

	return $msg;
    }

    /**
     *  Validate when update an user with below rules :
     * 	    -	If logged Account is not Super Admin, it does not have permission to update Super Admin account
     * @param type $model
     * @return \LGMessage
     */
    public function validateSuperAdmin($model) {
	$model->scenario = User::SCENARIO_UPDATE_USER;
	$msg = NULL;

	/* @var $loggedUser User */
	$loggedUser = User::model()->findByPk(app()->user->id);

	if (!$loggedUser->isSuperAdmin() && $model->isSuperAdmin()) {
	    $msg = new LGMessage(MsgType::ERROR, t('MSG_NOT_PERMISSION', 'messages'));
	} else if ($loggedUser->username != user()->superAdmin && $model->username == user()->superAdmin) {
	    $msg = new LGMessage(MsgType::ERROR, t('MSG_NOT_PERMISSION', 'messages'));
	} else if (!$loggedUser->isSuperAdmin() && !$loggedUser->isAdmin() && ($model->isSuperAdmin() || $model->isAdmin())) {
	    $msg = new LGMessage(MsgType::ERROR, t('MSG_NOT_PERMISSION', 'messages'));
	}

	return $msg;
    }

    /**
     * 
     * @param User $userModel
     * @return type
     */
    public function approvalButtonHtml($userModel) {
	//$id, $status, $action, $titleActive = 'Published', $titleInActive = 'Unpublished',
	// $classActive = 'icon active', $classInActive = 'icon inactive'
	if ($userModel->active || empty($userModel->active_code)) {
	    return '';
	} else {
	    $action = 'approval';
	    $id = $userModel->id;
	    $controller = Yii::app()->controller->id;

	    return Html::buttonInGrid(
			    "linkEdit", url($controller . "/" . $action, array('id' => $id)), "approval", "Foster City Lions  ", "icon approve-user update-dialog-open-link", "450", "250");
	}
    }

    public function editDialogButtonHtml($userModel, $dialogTitle, $dialogWidth, $dialogHeight) {
	$updateUrl = url(app()->controller->id . "/update/" . $userModel->id);

	return Html::buttonInGrid('linkEdit', $updateUrl, 'Edit', $dialogTitle, 'icon edit update-dialog-open-link', $dialogWidth, $dialogHeight);
    }

}

?>